<template>
  <div class="system-settings-page pph-page-container">
    <!-- 页面标题 -->
    <el-card class="page-header pph-page-header">
      <h2>
        <el-icon><Setting /></el-icon>
        系统设置
      </h2>
      <p>系统配置、数据导入导出、模板下载等功能</p>
    </el-card>

    <!-- 界面显示设置 -->
    <el-card class="ui-section" style="margin-bottom: 16px;">
      <template #header>
        <span>界面显示设置</span>
      </template>
      <el-form label-width="140px">
        <el-form-item label="悬浮统计条">
          <el-switch v-model="uiSettings.showFloatingBar" active-text="开启" inactive-text="关闭" />
        </el-form-item>
        <el-form-item label="统计条显示目标日期">
          <el-switch v-model="uiSettings.showTargetDateInBar" active-text="显示" inactive-text="隐藏" />
        </el-form-item>
        <el-form-item label="统计条始终悬浮">
          <el-switch v-model="uiSettings.barSticky" active-text="固定在底部" inactive-text="跟随页面" />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetUiDefaults">恢复默认</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据状态设置 -->
    <el-card class="state-section" style="margin-bottom: 16px;">
      <template #header>
        <span>数据状态设置</span>
      </template>
      <el-form label-width="140px">
        <el-form-item label="页面切换时保持筛选条件">
          <el-switch
            v-model="stateSettings.persistOnPageSwitch"
            active-text="保持"
            inactive-text="清空"
            @change="onPersistPageSwitchChange"
          />
          <div class="setting-description">
            开启后，在不同页面间切换时会保持筛选条件和查询状态
          </div>
        </el-form-item>
        <el-form-item label="重新打开浏览器时保持状态">
          <el-switch
            v-model="stateSettings.persistOnBrowserRestart"
            active-text="保持"
            inactive-text="清空"
            @change="onPersistBrowserRestartChange"
          />
          <div class="setting-description">
            开启后，关闭浏览器重新打开时会恢复上次的查询条件
          </div>
        </el-form-item>
        <el-form-item label="状态保存期限">
          <el-select v-model="stateSettings.expireDays" @change="onExpireDaysChange">
            <el-option label="1天" :value="1" />
            <el-option label="3天" :value="3" />
            <el-option label="7天" :value="7" />
            <el-option label="30天" :value="30" />
            <el-option label="永久保存" :value="0" />
          </el-select>
          <div class="setting-description">
            设置保存的查询状态多久后自动清除
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="clearAllStates" type="warning">清除所有保存的状态</el-button>
          <el-button @click="resetStateDefaults">恢复默认设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>


    <!-- Excel导入导出 -->
    <el-card class="excel-section">
      <template #header>
        <span>Excel数据导入导出</span>
      </template>

      <el-row :gutter="20">
        <!-- PPH目标值 -->
        <el-col :span="12">
          <el-card class="import-card">
            <template #header>
              <span>PPH目标值管理</span>
            </template>

            <div class="import-actions">
              <el-button type="primary" @click="downloadTemplate('targets')">
                <el-icon><Download /></el-icon>
                下载PPH目标值模板
              </el-button>

              <el-upload
                ref="targetUploadRef"
                :action="uploadUrl + '/targets'"
                :headers="uploadHeaders"
                name="file"
                :before-upload="beforeTargetUpload"
                :on-success="onTargetUploadSuccess"
                :on-error="onUploadError"
                :show-file-list="false"
                accept=".xlsx,.xls"
              >
                <el-button type="success">
                  <el-icon><Upload /></el-icon>
                  导入PPH目标值
                </el-button>
              </el-upload>
            </div>

            <el-divider />

            <div class="import-info">
              <h4>导入说明：</h4>
              <ul>
                <li><strong>必填字段</strong>：物料编码、产品名称、记录日期、节拍、标准人数、生产线</li>
                <li><strong>可选字段</strong>：产品系列、整机目标值、整机电机目标值</li>
                <li><strong>生产线支持多值</strong>：如"3、5"或"生产线A,生产线B"，系统会自动拆分</li>
                <li><strong>日期格式</strong>：YYYY-MM-DD 或 YYYY/MM/DD</li>
                <li><strong>数值要求</strong>：节拍、目标值、标准人数必须大于0</li>
              </ul>
            </div>
          </el-card>
        </el-col>

        <!-- PPH预估值 -->
        <el-col :span="12">
          <el-card class="import-card">
            <template #header>
              <span>PPH预估值管理</span>
            </template>

            <div class="import-actions">
              <el-button type="primary" @click="downloadTemplate('estimates')">
                <el-icon><Download /></el-icon>
                下载PPH预估值模板
              </el-button>

              <el-upload
                ref="estimateUploadRef"
                :action="uploadUrl + '/estimates'"
                :headers="uploadHeaders"
                name="file"
                :before-upload="beforeEstimateUpload"
                :on-success="onEstimateUploadSuccess"
                :on-error="onUploadError"
                :show-file-list="false"
                accept=".xlsx,.xls"
              >
                <el-button type="success">
                  <el-icon><Upload /></el-icon>
                  导入PPH预估值
                </el-button>
              </el-upload>
            </div>

            <el-divider />

            <div class="import-info">
              <h4>导入说明：</h4>
              <ul>
                <li><strong>必填字段</strong>：物料编码、产品名称、生产线、预估PPH值</li>
                <li><strong>数值要求</strong>：预估PPH值必须大于0</li>
                <li><strong>唯一性</strong>：同一物料+生产线组合唯一，匹配则更新，不匹配则新增</li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-divider />

      <!-- 任务队列面板 -->
      <el-row style="margin-top: 20px;">
        <el-col :span="24">
          <el-card>
            <template #header>
              <div style="display:flex;justify-content:space-between;align-items:center;">
                <span>后台任务队列（最近{{ jobs.length }}个）</span>
                <div>
                  <el-button size="small" @click="refreshJobs">刷新</el-button>
                  <el-button size="small" type="danger" @click="showClearJobsDialog" :disabled="jobs.length === 0">
                    清除记录
                  </el-button>
                </div>
              </div>
            </template>
            <el-table :data="jobs" size="small" height="240" :row-style="{height:'40px'}" @row-click="onJobRowClick">
              <el-table-column label="任务信息" min-width="280">
                <template #default="{row}">
                  <div class="job-info">
                    <div class="job-title">
                      <el-tag :type="getJobStatusType(row.status)" size="small">{{ getJobStatusText(row.status) }}</el-tag>
                      <span class="job-desc">{{ getJobDescription(row) }}</span>
                    </div>
                    <div class="job-meta">
                      <span class="job-time">{{ formatJobTime(row.created_at) }}</span>
                      <span class="job-id">ID: {{ row.id.split('-')[0] }}</span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="进度详情" width="200">
                <template #default="{row}">
                  <div class="progress-info">
                    <el-progress
                      :percentage="Math.min(100, Math.round((Number(row.processed||0)/Math.max(1,Number(row.total||1)))*100))"
                      :status="row.status==='failed'?'exception':(row.status==='completed'?'success':'')"
                      :stroke-width="6"
                    />
                    <div class="progress-text">
                      {{ row.processed || 0 }}/{{ row.total || 0 }}
                      <span v-if="row.updated">(更新{{ row.updated }})</span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="耗时" width="100">
                <template #default="{row}">
                  <span class="duration-text">{{ getJobDuration(row) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{row}">
                  <div class="job-actions">
                    <el-button link type="primary" @click="openJob(row.id)" size="small">查看详情</el-button>
                    <el-button
                      v-if="row.status === 'running'"
                      link
                      type="danger"
                      @click="confirmStopJob(row)"
                      size="small"
                      style="margin-left: 8px;"
                    >
                      🛑 停止
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>


      <el-row :gutter="20">
        <!-- PPH记录历史导入 -->
        <el-col :span="12">
          <el-card class="import-card">
            <template #header>
              <span>PPH记录历史导入</span>
            </template>
            <div class="import-actions">
              <el-button type="primary" @click="downloadTemplate('records')">
                <el-icon><Download /></el-icon>
                下载PPH记录历史导入模板
              </el-button>
              <el-upload
                :action="uploadUrl + '/records'"
                :headers="uploadHeaders"
                name="file"
                :before-upload="beforeRecordsUpload"
                :on-success="onRecordsUploadSuccess"
                :on-error="onUploadError"
                :show-file-list="false"
                accept=".xlsx,.xls"
              >
                <el-button type="success">
                  <el-icon><Upload /></el-icon>
                  导入PPH记录
                </el-button>
              </el-upload>
            </div>
            <el-divider />
            <div class="import-info">
              <h4>导入说明：</h4>
              <ul>
                <li><span class="required">必填字段</span>：记录日期、生产线、订单号、开始时间、结束时间、完成数量、物料编码、产品名称</li>
                <li><strong>人数字段</strong>：总人数必填，线上人员、线外人员可为空</li>
                <li><strong>时间字段</strong>：休息时间、转产时间、异常损失分钟等可为空</li>
                <li><strong>计算字段</strong>：净工作时间、实际节拍、PPH目标值、PPH实际等可为空，导入后系统重算</li>
                <li><strong>异常信息</strong>：异常分类、异常描述可为空</li>
                <li>模板文件名：PPH记录历史导入模板.xlsx</li>
              </ul>
              <el-alert
                title="净工作时间/实际节拍为计算项，历史导入时一律按系统规则重算，Excel中该两列可留空"
                type="warning"
                :closable="false"
                show-icon
                style="margin-top: 8px"
              />
            </div>
          </el-card>
        </el-col>
        <!-- 重算工具 -->
        <el-col :span="12">
          <el-card class="import-card">
            <template #header>
              <span>重算目标值/预估值/达成率（分批异步）</span>
            </template>
            <div class="recompute-form">
              <el-form :inline="true">
                <!-- 日期范围选择 - 新增 -->
                <div style="margin-bottom: 16px;">
                  <el-form-item label="重算日期范围">
                    <el-date-picker
                      v-model="recompute.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 280px"
                    />
                    <el-button
                      type="primary"
                      size="small"
                      @click="setDefaultDateRange"
                      style="margin-left: 8px"
                    >
                      默认1年
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      @click="clearDateRange"
                      style="margin-left: 4px"
                    >
                      全量重算
                    </el-button>
                  </el-form-item>
                </div>

                <!-- 其他筛选条件 -->
                <el-form-item label="记录日期">
                  <el-input v-model="recompute.record_date" placeholder="YYYY-MM-DD | 可留空" style="width: 160px" />
                </el-form-item>
                <el-form-item label="订单号">
                  <el-input v-model="recompute.order_number" placeholder="可留空" style="width: 180px" />
                </el-form-item>
                <el-form-item label="物料编码">
                  <el-input v-model="recompute.material_code" placeholder="可留空" style="width: 140px" />
                </el-form-item>
                <el-form-item label="生产线">
                  <el-input v-model="recompute.line_name" placeholder="可留空" style="width: 120px" />
                </el-form-item>
                <el-form-item>
                  <el-button type="warning" @click="triggerRecomputeJob" :loading="recompute.loading">
                    <el-icon><Setting /></el-icon>
                    启动重算任务
                  </el-button>
                </el-form-item>
              </el-form>
              <p class="tip">
                <strong>重算范围说明：</strong><br>
                • <span style="color: #409EFF;">默认1年</span>：推荐选项，重算近一年数据，速度快，覆盖常用数据<br>
                • <span style="color: #E6A23C;">全量重算</span>：重算所有历史数据，耗时较长，适用于数据修复<br>
                • 任务为分批异步执行，提供进度监控与取消功能
              </p>

              <!-- 任务进度显示 -->
              <div v-if="job.id" class="job-progress">
                <el-alert :title="`任务 ${job.id}：${job.status}`" type="info" :closable="false" show-icon />
                <el-progress :percentage="jobProgress" :status="job.status==='failed' ? 'exception' : (job.status==='completed' ? 'success' : undefined)" />
                <div class="job-actions">
                  <span>总数: {{ job.total }}，已处理: {{ job.processed }}，更新: {{ job.updated }}</span>
                  <div>
                    <el-button size="small" @click="openUpdatedInReports" :disabled="!jobFilterAvailable">查看更新记录</el-button>
                    <el-button size="small" type="danger" @click="cancelJob" :disabled="job.status!=='running'">取消任务</el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- PPH平均值重算工具 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card class="import-card">
            <template #header>
              <span>
                <el-icon><TrendCharts /></el-icon>
                PPH平均值重算（按分组计算）
              </span>
            </template>

            <div class="pph-recompute-section">
              <p style="margin: 0 0 16px 0; font-size: 14px; color: #606266;">
                <strong>计算公式：</strong>PPH平均值 = SUM(完工数量) ÷ (AVG(人数) × SUM(净工作时间) / 60)<br>
                <strong>分组规则：</strong>按同一日期、同一生产线、同一物料编码分组计算
              </p>

              <div class="pph-recompute-form">
                <el-form :inline="true">
                  <!-- PPH重算日期范围 -->
                  <div style="margin-bottom: 16px;">
                    <el-form-item label="PPH重算范围">
                      <el-date-picker
                        v-model="pphRecompute.dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        style="width: 280px"
                      />
                      <el-button
                        type="primary"
                        size="small"
                        @click="setPPHDefaultRange"
                        style="margin-left: 8px"
                      >
                        默认1个月
                      </el-button>
                      <el-button
                        type="warning"
                        size="small"
                        @click="clearPPHRange"
                        style="margin-left: 4px"
                      >
                        全量重算
                      </el-button>
                    </el-form-item>
                  </div>

                  <!-- PPH重算按钮 -->
                  <el-form-item>
                    <el-button type="success" @click="triggerPPHRecompute" :loading="pphRecompute.loading">
                      <el-icon><TrendCharts /></el-icon>
                      一键重算PPH平均值
                    </el-button>
                    <el-button type="info" @click="checkPPHSchedulerStatus" size="small">
                      <el-icon><Clock /></el-icon>
                      定时任务状态
                    </el-button>
                  </el-form-item>
                </el-form>

                <p class="tip">
                  <strong>PPH重算说明：</strong><br>
                  • <span style="color: #67C23A;">默认1个月</span>：推荐选项，重算近30天PPH平均值，速度快<br>
                  • <span style="color: #E6A23C;">全量重算</span>：重算所有历史PPH平均值，耗时较长<br>
                  • <span style="color: #409EFF;">自动更新</span>：系统每天12:00和19:00自动更新近7天的PPH平均值
                </p>

                <!-- PPH任务进度显示 -->
                <div v-if="pphJob.isRunning || pphJob.status === 'completed' || pphJob.status === 'error'" class="job-progress">
                  <el-alert
                    :title="getProgressTitle()"
                    :type="getProgressType()"
                    :closable="false"
                    show-icon
                  />

                  <!-- 进度条 -->
                  <el-progress
                    :percentage="pphJobProgress"
                    :status="getProgressStatus()"
                    :stroke-width="20"
                  >
                    <template #default="{ percentage }">
                      <span class="progress-text">{{ percentage }}%</span>
                    </template>
                  </el-progress>

                  <!-- 详细信息 -->
                  <div class="job-details" v-if="pphJob.isRunning || pphJob.total">
                    <div class="progress-info">
                      <span v-if="pphJob.current && pphJob.total">
                        进度: {{ pphJob.current }} / {{ pphJob.total }} 条记录
                      </span>
                      <span v-if="pphJob.estimatedTimeRemaining" class="time-remaining">
                        预计剩余: {{ formatTime(pphJob.estimatedTimeRemaining) }}
                      </span>
                    </div>

                    <!-- 当前处理记录 -->
                    <div v-if="pphJob.currentRecord" class="current-record">
                      <el-tag size="small" type="info">
                        正在处理: {{ pphJob.currentRecord.material_code }}@{{ pphJob.currentRecord.line_name }}
                        ({{ pphJob.currentRecord.record_date }})
                      </el-tag>
                    </div>
                  </div>

                  <!-- 完成后的统计 -->
                  <div v-if="pphJob.status === 'completed'" class="job-actions">
                    <span>✅ 重算完成！处理了 {{ pphJob.total }} 条记录</span>
                  </div>

                  <!-- 错误信息 -->
                  <div v-if="pphJob.status === 'error'" class="job-error">
                    <span>❌ 重算失败: {{ pphJob.error }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 导入结果显示 -->
    <el-card v-if="importResult" class="import-result">
      <template #header>
        <span>导入结果</span>
      </template>

      <el-alert
        :title="importResult.message"
        :type="importResult.success ? 'success' : 'error'"
        :closable="false"
        show-icon
      />

      <div v-if="importResult.details" class="result-details">
        <p><strong>成功：</strong>{{ importResult.successCount }} 条</p>
        <p><strong>失败：</strong>{{ importResult.errorCount }} 条</p>
        <p><strong>总计：</strong>{{ importResult.totalRecords }} 条</p>

        <div v-if="importResult.errors && importResult.errors.length > 0" class="error-list">
          <h4>错误详情：</h4>
          <ul>
            <li v-for="error in importResult.errors" :key="error" class="error-item">
              {{ error }}
            </li>
          </ul>
        </div>
      </div>
    </el-card>

    <!-- 系统信息 -->
    <el-card class="system-info">
      <template #header>
        <span>系统信息</span>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="系统版本">v1.0.0</el-descriptions-item>
        <el-descriptions-item label="数据库类型">SQLite3</el-descriptions-item>
        <el-descriptions-item label="前端端口">3010</el-descriptions-item>
        <el-descriptions-item label="后端端口">3011</el-descriptions-item>
        <el-descriptions-item label="支持格式">Excel (.xlsx, .xls)</el-descriptions-item>
        <el-descriptions-item label="最大文件">10MB</el-descriptions-item>

      </el-descriptions>
    </el-card>

    <!-- 任务详情对话框 -->
    <el-dialog v-model="jobDetailVisible" title="任务详情" width="600px" :close-on-click-modal="false">
      <div v-if="selectedJob.id" class="job-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="任务ID">{{ selectedJob.id }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getJobStatusType(selectedJob.status)">{{ getJobStatusText(selectedJob.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatFullTime(selectedJob.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatFullTime(selectedJob.started_at) }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ formatFullTime(selectedJob.finished_at) }}</el-descriptions-item>
          <el-descriptions-item label="耗时">{{ getJobDuration(selectedJob) }}</el-descriptions-item>
          <el-descriptions-item label="总记录数">{{ selectedJob.total || 0 }}</el-descriptions-item>
          <el-descriptions-item label="已处理">{{ selectedJob.processed || 0 }}</el-descriptions-item>
          <el-descriptions-item label="已更新">{{ selectedJob.updated || 0 }}</el-descriptions-item>
          <el-descriptions-item label="批次大小">{{ selectedJob.batch_size || 0 }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="selectedJob.status === 'running' || selectedJob.status === 'queued'" class="progress-section">
          <h4>执行进度</h4>
          <el-progress
            :percentage="Math.min(100, Math.round((Number(selectedJob.processed||0)/Math.max(1,Number(selectedJob.total||1)))*100))"
            :status="selectedJob.status==='failed'?'exception':(selectedJob.status==='completed'?'success':'')"
          />
          <p>{{ selectedJob.processed || 0 }} / {{ selectedJob.total || 0 }} ({{ Math.round((Number(selectedJob.processed||0)/Math.max(1,Number(selectedJob.total||1)))*100) }}%)</p>
        </div>

        <div v-if="selectedJob.filter_json" class="filter-section">
          <h4>筛选条件</h4>
          <pre class="filter-json">{{ formatFilterJson(selectedJob.filter_json) }}</pre>
        </div>

        <div v-if="selectedJob.error" class="error-section">
          <h4>错误信息</h4>
          <el-alert :title="selectedJob.error" type="error" :closable="false" />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="jobDetailVisible = false">关闭</el-button>
          <el-button v-if="selectedJob.status === 'running'" type="danger" @click="cancelSelectedJob">取消任务</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 清除记录对话框 -->
    <el-dialog v-model="clearJobsVisible" title="清除任务记录" width="500px" :close-on-click-modal="false">
      <div class="clear-jobs-content">
        <el-alert title="确认清除任务记录" type="warning" :closable="false" show-icon>
          <template #default>
            <p>此操作将清除历史任务记录，请选择清除范围：</p>
          </template>
        </el-alert>

        <el-form :model="clearJobsForm" label-width="120px" style="margin-top: 20px;">
          <el-form-item label="清除状态">
            <el-checkbox-group v-model="clearJobsForm.statuses">
              <el-checkbox label="completed">已完成</el-checkbox>
              <el-checkbox label="failed">失败</el-checkbox>
              <el-checkbox label="cancelled">已取消</el-checkbox>
              <el-checkbox label="running">运行中（谨慎使用）</el-checkbox>
            </el-checkbox-group>
            <div class="status-warning" v-if="clearJobsForm.statuses.includes('running')" style="margin-top: 12px;">
              <el-alert
                title="⚠️ 危险操作：清除运行中任务"
                type="error"
                :closable="false"
                show-icon
                size="small"
              >
                <template #default>
                  <p style="margin: 0; font-size: 12px; font-weight: bold; color: #f56c6c;">
                    🚨 强烈建议先手动停止运行中的任务，再清除记录！
                  </p>
                  <div style="margin-top: 8px;">
                    <el-checkbox v-model="clearJobsForm.cancelRunningFirst">
                      我已确认：先自动取消运行中的任务，再清除记录
                    </el-checkbox>
                  </div>
                  <div style="margin-top: 8px;">
                    <el-checkbox v-model="clearJobsForm.confirmDangerous">
                      我理解此操作的风险，确认要清除运行中的任务
                    </el-checkbox>
                  </div>
                </template>
              </el-alert>
            </div>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-radio-group v-model="clearJobsForm.timeRange">
              <el-radio label="all">全部</el-radio>
              <el-radio label="7">7天前</el-radio>
              <el-radio label="30">30天前</el-radio>
              <el-radio label="90">90天前</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <p class="clear-warning">
          <strong>注意：</strong>此操作不可恢复，建议只清除已完成的旧任务记录。
        </p>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="clearJobsVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClearJobs" :loading="clearJobsLoading">确认清除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Setting, Download, Upload, TrendCharts, Clock } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

import { pphService } from '@/services/pphService'

// 任务队列（脚本段）
const jobs = ref<any[]>([])
const jobsTimer = ref<any>(null)
async function refreshJobs(){
  try{
    const resp = await pphService.getRecomputeJobs(20)
    // 确保按创建时间降序排列（最新的在前面）
    const jobsList = resp?.jobs || []
    jobsList.sort((a: any, b: any) => {
      const timeA = new Date(a.created_at || 0).getTime()
      const timeB = new Date(b.created_at || 0).getTime()
      return timeB - timeA // 降序排列
    })
    jobs.value = jobsList

    // 检测僵尸任务（每次刷新时检查）
    showZombieTasksWarning()
  }catch(e){ console.warn('加载任务失败', e) }
}
function onJobRowClick(row:any){
  if (row && row.id) openJob(String(row.id))
}
function openJob(id:string){
  // 显示任务详情对话框
  const jobData = jobs.value.find(j => j.id === id)
  if (jobData) {
    selectedJob.value = { ...jobData }
    jobDetailVisible.value = true
    // 如果是运行中的任务，实时更新详情
    if (jobData.status === 'running') {
      refreshJobDetail(id)
    }
  }
}

// 任务详情对话框相关
const jobDetailVisible = ref(false)
const selectedJob = ref<any>({})

async function refreshJobDetail(id: string) {
  try {
    const resp = await pphService.getRecomputeJob(id)
    if (resp?.success && resp?.job) {
      selectedJob.value = { ...resp.job }
    }
  } catch (e) {
    console.warn('刷新任务详情失败', e)
  }
}

async function cancelSelectedJob() {
  try {
    if (!selectedJob.value?.id) return

    // 显示确认对话框
    const confirmed = await ElMessageBox.confirm(
      `确定要停止任务吗？\n\n` +
      `任务ID: ${selectedJob.value.id}\n` +
      `任务类型: ${formatJobDescription(selectedJob.value)}\n` +
      `当前进度: ${selectedJob.value.processed || 0}/${selectedJob.value.total || 0}\n\n` +
      `⚠️ 停止任务后：\n` +
      `• 当前处理将被中断\n` +
      `• 已处理的数据会保留\n` +
      `• 可以稍后重新启动任务`,
      '确认停止任务',
      {
        confirmButtonText: '确定停止',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).catch(() => false)

    if (!confirmed) return

    await pphService.cancelRecomputeJob(selectedJob.value.id)
    ElMessage.success('任务停止请求已发送')
    jobDetailVisible.value = false
    refreshJobs() // 刷新列表
  } catch (e) {
    console.error('取消任务失败:', e)
    ElMessage.error('停止任务失败')
  }
}

// 确认停止任务（从列表中）
async function confirmStopJob(job: any) {
  try {
    // 显示确认对话框
    const confirmed = await ElMessageBox.confirm(
      `确定要停止任务吗？\n\n` +
      `任务ID: ${job.id}\n` +
      `任务类型: ${formatJobDescription(job)}\n` +
      `当前进度: ${job.processed || 0}/${job.total || 0}\n` +
      `运行时长: ${getJobDuration(job)}\n\n` +
      `⚠️ 停止任务后：\n` +
      `• 当前处理将被中断\n` +
      `• 已处理的数据会保留\n` +
      `• 可以稍后重新启动任务`,
      '确认停止任务',
      {
        confirmButtonText: '确定停止',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).catch(() => false)

    if (!confirmed) return

    await pphService.cancelRecomputeJob(job.id)
    ElMessage.success('任务停止请求已发送')
    refreshJobs() // 刷新列表
  } catch (e) {
    console.error('停止任务失败:', e)
    ElMessage.error('停止任务失败')
  }
}

onMounted(()=>{
  refreshJobs()
  if (jobsTimer.value) clearInterval(jobsTimer.value)
  jobsTimer.value = setInterval(()=>{ refreshJobs().catch(()=>{}) }, 3000)
})

onUnmounted(()=>{ if (jobsTimer.value) clearInterval(jobsTimer.value) })

// 清除记录相关
const clearJobsVisible = ref(false)
const clearJobsLoading = ref(false)
const clearJobsForm = ref({
  statuses: ['completed', 'failed', 'cancelled'],
  timeRange: '30',
  cancelRunningFirst: true,
  confirmDangerous: false
})

function showClearJobsDialog() {
  clearJobsVisible.value = true
}

async function confirmClearJobs() {
  try {
    clearJobsLoading.value = true

    // 检查是否要清除运行中任务
    if (clearJobsForm.value.statuses.includes('running')) {
      // 检查是否确认了危险操作
      if (!clearJobsForm.value.confirmDangerous) {
        ElMessage.error('请确认您理解清除运行中任务的风险')
        clearJobsLoading.value = false
        return
      }

      // 显示最后确认对话框
      const confirmed = await showRunningTasksConfirmDialog()
      if (!confirmed) {
        clearJobsLoading.value = false
        return
      }

      // 如果启用了先取消功能
      if (clearJobsForm.value.cancelRunningFirst) {
        await cancelRunningJobsFirst()
      }
    }

    const payload: any = {
      statuses: clearJobsForm.value.statuses
    }

    if (clearJobsForm.value.timeRange !== 'all') {
      payload.older_than_days = parseInt(clearJobsForm.value.timeRange)
    }

    const response = await fetch(`${pphService.getApiUrl()}/api/admin/recompute/jobs/purge`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    })

    const result = await response.json()

    if (!response.ok) {
      throw new Error(result.error || '清除失败')
    }

    if (result.success) {
      ElMessage.success(`成功清除 ${result.deleted} 条任务记录`)
      clearJobsVisible.value = false
      refreshJobs() // 刷新列表
    } else {
      throw new Error(result.error || '清除失败')
    }

  } catch (e: any) {
    console.error('清除任务记录失败:', e)
    if (e.message?.includes('admin delete disabled')) {
      ElMessage.error('管理员删除功能未启用，请联系系统管理员')
    } else {
      ElMessage.error(`清除失败: ${e.message || e}`)
    }
  } finally {
    clearJobsLoading.value = false
  }
}

// 格式化任务描述
function formatJobDescription(job: any): string {
  const filter = job.filter_json ? JSON.parse(job.filter_json) : {}
  if (Object.keys(filter).length === 0) {
    return '全量重算任务'
  }

  const parts = []
  if (filter.record_date) parts.push(`日期:${filter.record_date}`)
  if (filter.line_names?.length) parts.push(`生产线:${filter.line_names.join(',')}`)
  if (filter.material_codes?.length) parts.push(`物料:${filter.material_codes.join(',')}`)
  if (filter.order_number) parts.push(`订单:${filter.order_number}`)

  return parts.length > 0 ? `条件重算(${parts.join(', ')})` : '重算任务'
}

// 显示运行中任务确认对话框
async function showRunningTasksConfirmDialog(): Promise<boolean> {
  const runningJobs = jobs.value.filter(job => job.status === 'running')

  if (runningJobs.length === 0) {
    return true
  }

  return new Promise((resolve) => {
    ElMessageBox.confirm(
      `检测到 ${runningJobs.length} 个运行中的任务：\n\n` +
      runningJobs.map(job => `• ${job.id} - ${formatJobDescription(job)}`).join('\n') +
      `\n\n⚠️ 清除运行中的任务可能导致：\n` +
      `• 数据处理中断\n` +
      `• 数据不一致\n` +
      `• 系统状态异常\n\n` +
      `🔧 建议操作：\n` +
      `1. 先手动停止这些任务\n` +
      `2. 等待任务正常结束\n` +
      `3. 再清除记录\n\n` +
      `确定要继续清除吗？`,
      '⚠️ 危险操作确认',
      {
        confirmButtonText: '我确定要清除',
        cancelButtonText: '取消，我先手动停止',
        type: 'error',
        dangerouslyUseHTMLString: false,
        showClose: false
      }
    ).then(() => {
      resolve(true)
    }).catch(() => {
      resolve(false)
    })
  })
}

// 先取消运行中的任务
async function cancelRunningJobsFirst() {
  try {
    // 获取所有运行中的任务
    const runningJobs = jobs.value.filter(job => job.status === 'running')

    if (runningJobs.length === 0) {
      return
    }

    ElMessage.info(`正在取消 ${runningJobs.length} 个运行中的任务...`)

    // 并发取消所有运行中的任务
    const cancelPromises = runningJobs.map(job =>
      fetch(`${pphService.getApiUrl()}/api/recompute/jobs/${job.id}/cancel`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      })
    )

    await Promise.all(cancelPromises)

    // 等待一下让状态更新
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success(`成功取消 ${runningJobs.length} 个运行中的任务`)

  } catch (e: any) {
    console.error('取消运行中任务失败:', e)
    throw new Error(`取消运行中任务失败: ${e.message || e}`)
  }
}

// 已通知的僵尸任务ID集合，避免重复通知
const notifiedZombieJobs = ref<Set<string>>(new Set())

// 检测僵尸任务
function detectZombieJobs(jobsList: any[]): any[] {
  const now = new Date()
  const zombieThreshold = 4 * 60 * 60 * 1000 // 4小时无更新视为僵尸任务（提高阈值）

  return jobsList.filter(job => {
    // 只检查正在运行的任务
    if (job.status !== 'running') return false

    // 检查任务是否长时间无更新
    const startedAt = new Date(job.started_at || job.created_at)
    const timeSinceStart = now.getTime() - startedAt.getTime()

    // 如果运行超过4小时，可能是僵尸任务
    if (timeSinceStart > zombieThreshold) {
      console.warn(`🧟 检测到僵尸任务: ${job.id}, 运行时间: ${Math.round(timeSinceStart / 1000 / 60)}分钟`);
      return true
    }

    return false
  })
}

// 停止僵尸任务
// 停止僵尸任务 (暂时注释，避免未使用警告)
// async function stopZombieJob(jobId: string) {
//   try {
//     await pphService.cancelRecomputeJob(jobId)
//     ElMessage.success('僵尸任务已停止')

//     // 从已通知集合中移除
//     notifiedZombieJobs.value.delete(jobId)

//     // 刷新任务列表
//     await refreshJobs()
//   } catch (error) {
//     console.error('停止僵尸任务失败:', error)
//     ElMessage.error('停止僵尸任务失败')
//   }
// }



// 显示僵尸任务警告（优化版：避免重复通知，提供操作按钮）
function showZombieTasksWarning() {
  const zombieJobs = detectZombieJobs(jobs.value)

  // 过滤出未通知过的僵尸任务
  const newZombieJobs = zombieJobs.filter(job => !notifiedZombieJobs.value.has(job.id))

  if (newZombieJobs.length > 0) {
    // 记录已通知的任务
    newZombieJobs.forEach(job => notifiedZombieJobs.value.add(job.id))

    console.warn(`🧟 发现 ${newZombieJobs.length} 个僵尸任务:`, newZombieJobs.map(job => ({
      id: job.id,
      status: job.status,
      started_at: job.started_at,
      created_at: job.created_at
    })));

    // 只有在PPH重算任务正在运行时才显示清理提示
    if (pphJob.value.isRunning) {
      // 创建带操作按钮的通知
      ElNotification({
        title: '🧟 检测到可能的僵尸任务',
        message: `发现 ${newZombieJobs.length} 个长时间运行的任务，PPH重算任务可能卡住。`,
        type: 'warning',
        duration: 20000,
        position: 'bottom-right',
        showClose: true
      })

      // 显示操作提示
      ElMessageBox.confirm(
        'PPH重算任务可能卡住，是否需要清理任务状态？',
        '僵尸任务处理',
        {
          confirmButtonText: '清理PPH重算任务',
          cancelButtonText: '稍后处理',
          type: 'warning',
          showClose: true
        }
      ).then(() => {
        cleanupPPHRecomputeTask()
      }).catch(() => {
        console.log('用户取消清理僵尸任务')
      })
    } else {
      // 如果PPH重算任务没有运行，只记录日志，不弹出提示
      console.warn('🧟 检测到僵尸任务，但PPH重算任务未运行，可能是历史任务记录');
    }
  }

  // 清理已完成或取消的任务的通知记录
  const runningJobIds = new Set(jobs.value.filter(job => job.status === 'running').map(job => job.id))
  notifiedZombieJobs.value.forEach(jobId => {
    if (!runningJobIds.has(jobId)) {
      notifiedZombieJobs.value.delete(jobId)
    }
  })
}

// 清理PPH重算任务状态
async function cleanupPPHRecomputeTask() {
  try {
    console.log('🧹 清理PPH重算任务状态...')

    const response = await fetch(`${pphService.getApiUrl()}/api/pph/recompute/cleanup`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const result = await response.json()
      ElMessage.success(result.message || 'PPH重算任务状态已清理')

      // 清理前端状态
      pphJob.value = {
        isRunning: false,
        current: 0,
        total: 0,
        percentage: 0,
        status: 'idle',
        error: undefined
      }

      // 停止进度轮询
      stopProgressPolling()

      // 刷新任务列表
      await refreshJobs()
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

  } catch (error: any) {
    console.error('清理PPH重算任务失败:', error)
    ElMessage.error('清理PPH重算任务失败: ' + (error?.message || String(error)))
  }
}

interface ImportResult {
  success: boolean
  message: string
  successCount?: number
  errorCount?: number
  totalRecords?: number
  errors?: string[]
  details?: any
}

// 重算任务状态
const job = ref<any>({})
const jobTimer = ref<any>(null)
const jobProgress = computed(() => {
  const t = Number(job.value?.total || 0)
  const p = Number(job.value?.processed || 0)
  if (!t) return 0
  return Math.min(100, Math.round((p / t) * 100))
})
const jobFilterAvailable = computed(() => !!job.value?.filter_json)



// 状态
const importResult = ref<ImportResult | null>(null)
const targetUploadRef = ref()
const estimateUploadRef = ref()

// 重算表单状态
const recompute = ref<{
  from_date?: string;
  to_date?: string;
  line_name?: string;
  material_code?: string;
  record_date?: string;
  order_number?: string;
  loading?: boolean;
  dateRange?: [string, string] | null;
}>({
  loading: false,
  dateRange: null
})

// PPH重算表单状态
const pphRecompute = ref<{
  dateRange?: [string, string] | null;
  loading?: boolean;
}>({
  loading: false,
  dateRange: null
})

// 页面挂载时不设置默认值，让用户手动选择
onMounted(() => {
  // 不自动设置日期范围，让用户手动选择或点击快捷按钮
  // 这样日历默认不会打开，用户体验更好
})

// PPH重算任务状态
const pphJob = ref<{
  id?: string;
  status?: string;
  groupCount?: number;
  updatedCount?: number;
  isRunning?: boolean;
  current?: number;
  total?: number;
  percentage?: number;
  currentRecord?: any;
  estimatedTimeRemaining?: number;
  error?: string;
}>({})

// PPH任务进度
const pphJobProgress = computed(() => {
  // 如果有实时进度，使用实时进度
  if (pphJob.value.percentage !== undefined) {
    return pphJob.value.percentage
  }
  // 否则使用完成后的统计
  if (!pphJob.value.groupCount || pphJob.value.groupCount === 0) return 0
  return Math.round((pphJob.value.updatedCount || 0) / pphJob.value.groupCount * 100)
})

// 进度轮询定时器
let progressTimer: number | null = null

// 轮询进度
async function pollProgress() {
  try {
    const response = await fetch(`${pphService.getApiUrl()}/api/pph/recompute/progress`)
    if (response.ok) {
      const progress = await response.json()

      // 更新进度状态
      pphJob.value = {
        ...pphJob.value,
        isRunning: progress.isRunning,
        current: progress.current,
        total: progress.total,
        percentage: progress.percentage,
        currentRecord: progress.currentRecord,
        estimatedTimeRemaining: progress.estimatedTimeRemaining,
        status: progress.status,
        error: progress.error
      }

      // 如果任务完成或失败，停止轮询
      if (!progress.isRunning) {
        stopProgressPolling()
        if (progress.status === 'completed') {
          ElMessage.success(`PPH重算完成！处理了 ${progress.total} 条记录`)
        } else if (progress.status === 'error') {
          ElMessage.error(`PPH重算失败: ${progress.error || '未知错误'}`)

          // 如果是超时错误，提示用户可以清理任务状态
          if (progress.error && progress.error.includes('超时')) {
            ElMessageBox.confirm(
              '检测到PPH重算任务超时，是否清理任务状态以便重新开始？',
              '任务超时处理',
              {
                confirmButtonText: '清理任务状态',
                cancelButtonText: '稍后处理',
                type: 'warning'
              }
            ).then(() => {
              cleanupPPHRecomputeTask()
            }).catch(() => {
              console.log('用户取消清理超时任务')
            })
          }
        }
      }
    } else {
      console.warn(`轮询进度失败: HTTP ${response.status}`)
      // 如果连续失败多次，停止轮询
      if (response.status >= 500) {
        stopProgressPolling()
        ElMessage.error('服务器错误，已停止进度轮询')
      }
    }
  } catch (error) {
    console.warn('轮询进度失败:', error)
    // 网络错误不停止轮询，继续尝试
  }
}

// 开始进度轮询
function startProgressPolling() {
  if (progressTimer) {
    clearInterval(progressTimer)
  }
  progressTimer = setInterval(pollProgress, 1000) // 每秒轮询一次
}

// 停止进度轮询
function stopProgressPolling() {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
}

// 获取进度标题
function getProgressTitle() {
  if (pphJob.value.isRunning) {
    return `PPH重算进行中... (${pphJob.value.current || 0}/${pphJob.value.total || 0})`
  } else if (pphJob.value.status === 'completed') {
    return 'PPH重算已完成'
  } else if (pphJob.value.status === 'error') {
    return 'PPH重算失败'
  }
  return 'PPH重算任务'
}

// 获取进度类型
function getProgressType() {
  if (pphJob.value.isRunning) {
    return 'info'
  } else if (pphJob.value.status === 'completed') {
    return 'success'
  } else if (pphJob.value.status === 'error') {
    return 'error'
  }
  return 'info'
}

// 获取进度条状态
function getProgressStatus() {
  if (pphJob.value.status === 'error') {
    return 'exception'
  } else if (pphJob.value.status === 'completed') {
    return 'success'
  }
  return undefined
}

// 格式化时间
function formatTime(seconds: number) {
  if (seconds < 60) {
    return `${seconds}秒`
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}分${remainingSeconds}秒`
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return `${hours}小时${minutes}分钟`
  }
}

// 设置默认1年日期范围
function setDefaultDateRange() {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setFullYear(endDate.getFullYear() - 1)

  recompute.value.dateRange = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]

  ElMessage.success('已设置为近1年数据范围')
}

// 清除日期范围（全量重算）
function clearDateRange() {
  recompute.value.dateRange = null
  ElMessage.warning('已设置为全量重算，将处理所有历史数据')
}

// 设置PPH重算默认1个月范围
function setPPHDefaultRange() {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setMonth(endDate.getMonth() - 1)

  pphRecompute.value.dateRange = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]

  ElMessage.success('已设置为近1个月PPH重算范围')
}

// 清除PPH重算日期范围（全量重算）
function clearPPHRange() {
  pphRecompute.value.dateRange = null
  ElMessage.warning('已设置为全量PPH重算，将处理所有历史数据')
}

// 触发PPH重算任务
async function triggerPPHRecompute() {
  try {
    pphRecompute.value.loading = true

    // 重置进度状态
    pphJob.value = {
      isRunning: false,
      current: 0,
      total: 0,
      percentage: 0,
      status: 'idle'
    }

    const payload: any = {}

    // 设置重算范围
    if (pphRecompute.value.dateRange && pphRecompute.value.dateRange.length === 2) {
      payload.startDate = pphRecompute.value.dateRange[0]
      payload.endDate = pphRecompute.value.dateRange[1]
      payload.fullRange = false
    } else {
      payload.fullRange = true
    }

    // 显示重算范围信息
    const rangeInfo = payload.fullRange
      ? '全量PPH重算（所有历史数据）'
      : `PPH重算范围: ${payload.startDate} 至 ${payload.endDate}`

    console.log('PPH重算任务参数:', payload)
    ElMessage.info(`启动PPH重算任务 - ${rangeInfo}`)

    // 开始进度轮询
    startProgressPolling()

    // 调用正确的PPH重算API
    const response = await fetch(`${pphService.getApiUrl()}/api/pph/recompute`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    })

    if (!response.ok) {
      // 检查是否是409冲突（已有任务在运行）
      if (response.status === 409) {
        const errorResult = await response.json().catch(() => ({}))
        ElMessage.warning(errorResult.error || '已有重算任务正在运行')
        // 如果有任务在运行，继续轮询进度
        return
      }

      // 其他错误，停止轮询并显示错误
      stopProgressPolling()
      const errorText = await response.text().catch(() => response.statusText)
      throw new Error(`HTTP ${response.status}: ${errorText}`)
    }

    const result = await response.json()

    if (result.success) {
      // 任务启动成功，继续轮询进度
      console.log('PPH重算任务启动成功:', result)
      ElMessage.success('PPH重算任务已启动，正在处理中...')
    } else {
      // 任务启动失败，停止轮询
      stopProgressPolling()
      throw new Error(result.message || result.error || 'PPH重算启动失败')
    }

  } catch (error) {
    console.error('PPH重算失败:', error)
    ElMessage.error(`PPH重算失败: ${(error as Error).message}`)
    pphJob.value = {
      status: 'failed',
      error: (error as Error).message
    }
    stopProgressPolling()
  } finally {
    pphRecompute.value.loading = false
  }
}

// 检查PPH定时任务状态
async function checkPPHSchedulerStatus() {
  try {
    const response = await fetch(`${pphService.getApiUrl()}/api/pph/scheduler/status`)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const status = await response.json()

    const statusInfo = `
定时任务状态：
• 运行状态: ${status.isRunning ? '运行中' : '空闲'}
• 上次更新: ${status.lastUpdateTime ? new Date(status.lastUpdateTime).toLocaleString() : '未执行'}
• 更新范围: ${status.updateRange}天
• 执行时间: 每天12:00和19:00
    `.trim()

    ElMessageBox.alert(statusInfo, 'PPH定时任务状态', {
      confirmButtonText: '确定',
      type: 'info'
    })

  } catch (error) {
    console.error('获取PPH定时任务状态失败:', error)
    ElMessage.error(`获取状态失败: ${(error as Error).message}`)
  }
}

// 初始化时不设置默认范围，让用户手动选择
onMounted(() => {
  // 不自动设置日期范围，改善用户体验
  // setDefaultDateRange()
  // setPPHDefaultRange()
})

// 组件销毁时清理定时器
onUnmounted(() => {
  stopProgressPolling()
})

// 计算属性
const uploadUrl = computed(() => `${pphService.getApiUrl()}/api/excel/import`)
const uploadHeaders = computed(() => ({}))

// 方法
async function downloadTemplate(type: 'targets' | 'estimates' | 'records') {
  try {
    const templateNames: Record<'targets' | 'estimates' | 'records', string> = {
      targets: 'PPH目标值导入模板',
      estimates: 'PPH预估值导入模板',
      records: 'PPH记录历史导入模板'
    }
    const templateName = templateNames[type] || 'PPH导入模板'

    const response = await fetch(`${pphService.getApiUrl()}/api/excel/template/${type}`)

    if (!response.ok) {
      throw new Error('下载失败')
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${templateName}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success(`${templateName}下载成功`)
  } catch (error: any) {
    ElMessage.error('模板下载失败: ' + (error?.message || String(error)))
  }
}

function beforeTargetUpload(file: File) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel' ||
                  file.name.endsWith('.xlsx') ||
                  file.name.endsWith('.xls')

  if (!isExcel) {
    ElMessage.error('只支持Excel文件格式(.xlsx, .xls)')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }

  ElMessage.info('正在上传PPH目标值文件...')
  return true
}


// 界面显示设置脚本（从样式段移出，放到脚本段）
const uiSettings = ref({
  showFloatingBar: (localStorage.getItem('pph_show_floating_bar') ?? '1') !== '0',
  showTargetDateInBar: (localStorage.getItem('pph_show_target_date_in_bar') ?? '1') !== '0',
  barSticky: (localStorage.getItem('pph_fpb_sticky') ?? '1') !== '0'
})
watch(() => uiSettings.value.barSticky, v => localStorage.setItem('pph_fpb_sticky', v ? '1' : '0'))

function persistUiSettings(){
  localStorage.setItem('pph_show_floating_bar', uiSettings.value.showFloatingBar ? '1' : '0')
  localStorage.setItem('pph_show_target_date_in_bar', uiSettings.value.showTargetDateInBar ? '1' : '0')
}
watch(uiSettings, persistUiSettings, { deep: true })
function resetUiDefaults(){
  uiSettings.value = { showFloatingBar: true, showTargetDateInBar: true, barSticky: true }
  persistUiSettings()
  localStorage.setItem('pph_fpb_sticky', '1')
  ElMessage.success('已恢复界面显示默认设置')
}

// —— 界面显示设置脚本结束 ——

// 数据状态设置
const stateSettings = ref({
  persistOnPageSwitch: (localStorage.getItem('pph_persist_page_switch') ?? '1') === '1',
  persistOnBrowserRestart: (localStorage.getItem('pph_persist_browser_restart') ?? '1') === '1',
  // 默认改为1天
  expireDays: parseInt(localStorage.getItem('pph_state_expire_days') ?? '1')
})

// 状态设置变化处理
function onPersistPageSwitchChange(value: boolean) {
  localStorage.setItem('pph_persist_page_switch', value ? '1' : '0')
  if (!value) {
    // 如果关闭页面切换保持，清除当前保存的状态
    clearAllStates()
  }
  ElMessage.success(value ? '已开启页面切换状态保持' : '已关闭页面切换状态保持')
}

function onPersistBrowserRestartChange(value: boolean) {
  localStorage.setItem('pph_persist_browser_restart', value ? '1' : '0')
  if (!value) {
    // 如果关闭浏览器重启保持，清除当前保存的状态
    clearAllStates()
  }
  ElMessage.success(value ? '已开启浏览器重启状态保持' : '已关闭浏览器重启状态保持')
}

function onExpireDaysChange(value: number) {
  localStorage.setItem('pph_state_expire_days', value.toString())
  ElMessage.success(`状态保存期限已设置为${value === 0 ? '永久保存' : value + '天'}`)
}

// 清除所有保存的状态
function clearAllStates() {
  const keysToRemove = []
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (key && (key.startsWith('pph_search_') || key.startsWith('pph_page_'))) {
      keysToRemove.push(key)
    }
  }
  keysToRemove.forEach(key => localStorage.removeItem(key))
  ElMessage.success(`已清除${keysToRemove.length}个保存的状态`)
}

// 恢复状态设置默认值
function resetStateDefaults() {
  stateSettings.value = {
    persistOnPageSwitch: true,
    persistOnBrowserRestart: true,
    expireDays: 1
  }
  localStorage.setItem('pph_persist_page_switch', '1')
  localStorage.setItem('pph_persist_browser_restart', '1')
  localStorage.setItem('pph_state_expire_days', '1')
  ElMessage.success('已恢复状态设置默认值')
}

// —— 数据状态设置脚本结束 ——

function beforeEstimateUpload(file: File) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel' ||
                  file.name.endsWith('.xlsx') ||
                  file.name.endsWith('.xls')

  if (!isExcel) {
    ElMessage.error('只支持Excel文件格式(.xlsx, .xls)')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }

  ElMessage.info('正在上传PPH预估值文件...')
  return true
}

function beforeRecordsUpload(file: File) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel' ||
                  file.name.endsWith('.xlsx') ||
                  file.name.endsWith('.xls')
  if (!isExcel) {
    ElMessage.error('只支持Excel文件格式(.xlsx, .xls)')
    return false
  }
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  ElMessage.info('正在上传PPH记录文件...')
  return true
}

function onRecordsUploadSuccess(response: any) {
  importResult.value = {
    ...response,
    details: response
  }
  if (response.success) {
    ElMessage.success({ message: `PPH记录导入成功！成功导入 ${response.successCount} 条数据`, duration: 5000 })

    // 处理重算建议（新机制）
    if (response.recomputeSuggestion) {
      const suggestion = response.recomputeSuggestion

      if (suggestion.recommended && suggestion.payload) {
        // 显示重算建议对话框
        ElMessageBox.confirm(
          suggestion.message || `建议重算 ${suggestion.estimatedRecords} 条受影响的记录`,
          '重算建议',
          {
            confirmButtonText: '立即重算',
            cancelButtonText: '稍后手动重算',
            type: 'info',
            distinguishCancelAndClose: true
          }
        ).then(async () => {
          // 用户选择立即重算
          try {
            const recomputeResponse = await pphService.startRecomputeJob(suggestion.payload)

            if (recomputeResponse && recomputeResponse.success) {
              ElMessage.success(recomputeResponse.message || '重算任务已启动')

              // 显示任务进度
              job.value = {
                id: recomputeResponse.job_id,
                status: 'queued',
                total: recomputeResponse.total || 0,
                processed: 0,
                updated: 0
              }

              if (jobTimer.value) clearInterval(jobTimer.value)
              jobTimer.value = setInterval(async () => {
                try {
                  const st = await pphService.getRecomputeJob(job.value.id)
                  if (st?.success && st?.job) {
                    job.value = { ...st.job }
                    if (['completed','failed','cancelled'].includes(job.value.status)) {
                      clearInterval(jobTimer.value)
                      jobTimer.value = null
                    }
                  }
                } catch {}
              }, 1000) // 优化：减少轮询间隔到1秒
            } else {
              ElMessage.error('启动重算任务失败')
            }
          } catch (error) {
            console.error('启动重算任务失败:', error)
            ElMessage.error('启动重算任务失败')
          }
        }).catch((action) => {
          if (action === 'cancel') {
            ElMessage.info('您可以稍后在"重算工具"中手动启动重算')
          }
        })
      } else {
        // 无需重算
        ElMessage.info(suggestion.message || '导入完成，无需重算')
      }
    }

    // 兼容旧的自动重算机制（如果存在）
    else if (response.autoRecompute?.started && response.autoRecompute.job_id) {
      job.value = { id: response.autoRecompute.job_id, status: 'queued', total: response.autoRecompute.total || 0, processed: 0, updated: 0 }
      if (jobTimer.value) clearInterval(jobTimer.value)
      jobTimer.value = setInterval(async () => {
        try {
          const st = await pphService.getRecomputeJob(job.value.id)
          if (st?.success && st?.job) {
            job.value = { ...st.job }
            if (['completed','failed','cancelled'].includes(job.value.status)) {
              clearInterval(jobTimer.value)
              jobTimer.value = null
            }
          }
        } catch {}
      }, 1000) // 优化：减少轮询间隔到1秒
    }
  } else {
    ElMessage.error(response.message || '导入失败')
  }
}

function onTargetUploadSuccess(response: any) {
  importResult.value = {
    ...response,
    details: response
  }

  if (response.success) {
    ElMessage.success({
      message: `PPH目标值导入成功！成功导入 ${response.successCount} 条数据`,
      duration: 5000
    })

    // 自动显示导入后后台重算任务进度（若已启动）
    if (response.autoRecompute?.started && response.autoRecompute.job_id) {
      job.value = { id: response.autoRecompute.job_id, status: 'queued', total: response.autoRecompute.total || 0, processed: 0, updated: 0 }
      if (jobTimer.value) clearInterval(jobTimer.value)
      jobTimer.value = setInterval(async () => {
        try {
          const st = await pphService.getRecomputeJob(job.value.id)
          if (st?.success && st?.job) {
            job.value = { ...st.job }
            if (['completed','failed','cancelled'].includes(job.value.status)) {
              clearInterval(jobTimer.value)
              jobTimer.value = null
            }
          }
        } catch {}
      }, 1000) // 优化：减少轮询间隔到1秒
    }
  } else {
    ElMessage.error('PPH目标值导入失败')
  }
}

function onEstimateUploadSuccess(response: any) {
  importResult.value = {
    ...response,
    details: response
  }

  if (response.success) {
    ElMessage.success('PPH预估值导入成功')
    // 自动显示导入后后台重算任务进度（若已启动）
    if (response.autoRecompute?.started && response.autoRecompute.job_id) {
      job.value = { id: response.autoRecompute.job_id, status: 'queued', total: response.autoRecompute.total || 0, processed: 0, updated: 0 }
      if (jobTimer.value) clearInterval(jobTimer.value)
      jobTimer.value = setInterval(async () => {
        try {
          const st = await pphService.getRecomputeJob(job.value.id)
          if (st?.success && st?.job) {
            job.value = { ...st.job }
            if (['completed','failed','cancelled'].includes(job.value.status)) {
              clearInterval(jobTimer.value)
              jobTimer.value = null
            }
          }
        } catch {}
      }, 1000) // 优化：减少轮询间隔到1秒
    }
  } else {
    ElMessage.error('PPH预估值导入失败')
  }
}

function onUploadError(error: any) {
  console.error('上传失败:', error)
  ElMessage.error('文件上传失败')
  importResult.value = {
    success: false,
    message: '文件上传失败: ' + (error?.message || String(error))
  }
}

async function triggerRecomputeJob() {
  try {
    recompute.value.loading = true
    const payload: any = {}

    // 优先使用日期范围
    if (recompute.value.dateRange && recompute.value.dateRange.length === 2) {
      payload.from_date = recompute.value.dateRange[0]
      payload.to_date = recompute.value.dateRange[1]
    }

    // 其他筛选条件
    if (recompute.value.record_date) payload.record_date = recompute.value.record_date
    if (recompute.value.order_number) payload.order_number = recompute.value.order_number
    if (recompute.value.line_name) payload.line_name = recompute.value.line_name
    if (recompute.value.material_code) payload.material_code = recompute.value.material_code

    // 显示重算范围信息
    const rangeInfo = payload.from_date && payload.to_date
      ? `日期范围: ${payload.from_date} 至 ${payload.to_date}`
      : '全量重算（所有历史数据）'

    console.log('重算任务参数:', payload)
    ElMessage.info(`启动重算任务 - ${rangeInfo}`)

    const resp = await pphService.startRecomputeJob(payload)
    if (!resp?.success) throw new Error(resp?.error || '启动任务失败')
    job.value = { id: resp.job_id, status: 'queued', total: resp.total, processed: 0, updated: 0 }
    ElMessage.success(`已启动重算任务，jobId=${resp.job_id}，总数=${resp.total}`)

    // 开始轮询
    if (jobTimer.value) clearInterval(jobTimer.value)
    jobTimer.value = setInterval(async () => {
      try {
        const st = await pphService.getRecomputeJob(job.value.id)
        if (st?.success && st?.job) {
          job.value = { ...st.job }
          if (['completed','failed','cancelled'].includes(job.value.status)) {
            clearInterval(jobTimer.value)
            jobTimer.value = null
            if (job.value.status === 'completed') {
              ElMessage.success(`重算完成，更新 ${job.value.updated}/${job.value.total} 条`)
            } else if (job.value.status === 'failed') {
              ElMessage.error(`重算失败: ${job.value.error || ''}`)
            }
          }
        }
      } catch (e) {
        console.warn('获取任务状态失败', e)
      }
    }, 1000) // 优化：减少轮询间隔到1秒
  } catch (e: any) {
    ElMessage.error(e?.message || '重算启动失败')
  } finally {
    recompute.value.loading = false
  }
}

function openUpdatedInReports() {
  // 尝试从任务的 filter_json 构造路由查询
  try {
    const raw = job.value?.filter_json ? JSON.parse(job.value.filter_json) : {}
    const query: any = {}
    if (raw.from_date) query.start_date = raw.from_date
    if (raw.to_date) query.end_date = raw.to_date
    if (raw.line_name) query.line_name = raw.line_name
    if (Array.isArray(raw.line_names) && raw.line_names.length) query.line_name = raw.line_names[0]
    if (raw.material_code) query.material_code = raw.material_code
    if (Array.isArray(raw.material_codes) && raw.material_codes.length) query.material_code = raw.material_codes[0]

    window.location.href = `/reports?${new URLSearchParams(query).toString()}`
  } catch (e) {
    console.error('构建报表链接失败:', e)
    window.location.href = '/reports'
  }
}

async function cancelJob() {
  try {
    if (!job.value?.id) return
    await pphService.cancelRecomputeJob(job.value.id)
    ElMessage.success('任务已请求取消')
  } catch (e) {
    console.error('取消任务失败:', e)
    ElMessage.error('取消任务失败')
  }
}

// 任务队列显示优化函数
function getJobStatusType(status: string): string {
  switch (status) {
    case 'completed': return 'success'
    case 'failed': return 'danger'
    case 'running': return 'warning'
    case 'queued': return 'info'
    case 'cancelled': return ''
    default: return 'info'
  }
}

function getJobStatusText(status: string): string {
  switch (status) {
    case 'completed': return '已完成'
    case 'failed': return '失败'
    case 'running': return '运行中'
    case 'queued': return '排队中'
    case 'cancelled': return '已取消'
    default: return status || '未知'
  }
}

function getJobDescription(row: any): string {
  try {
    const filter = row.filter_json ? JSON.parse(row.filter_json) : {}
    const parts = []

    if (filter.record_date) parts.push(`日期:${filter.record_date}`)
    if (filter.order_number) parts.push(`订单:${filter.order_number}`)
    if (filter.material_code) parts.push(`物料:${filter.material_code}`)
    if (filter.line_name) parts.push(`生产线:${filter.line_name}`)

    if (parts.length === 0) {
      return '全量重算任务'
    }

    return `重算任务 (${parts.join(', ')})`
  } catch (e) {
    console.warn('解析任务描述失败:', e)
    return '重算任务'
  }
}

function formatJobTime(timeStr: string): string {
  if (!timeStr) return ''
  try {
    // 修复时区问题：确保正确解析数据库时间
    let date: Date
    if (timeStr.includes('T') || timeStr.includes('Z')) {
      // ISO格式时间，直接解析
      date = new Date(timeStr)
    } else {
      // SQLite格式时间，需要添加时区信息
      date = new Date(timeStr + 'Z') // 假设数据库存储的是UTC时间
    }

    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffMins = Math.floor(diffMs / (1000 * 60))
    const diffHours = Math.floor(diffMins / 60)
    const diffDays = Math.floor(diffHours / 24)

    if (diffDays > 0) return `${diffDays}天前`
    if (diffHours > 0) return `${diffHours}小时前`
    if (diffMins > 0) return `${diffMins}分钟前`
    return '刚刚'
  } catch (e) {
    console.warn('格式化时间失败:', e, 'timeStr:', timeStr)
    return timeStr.slice(0, 16) // 返回前16个字符作为备选
  }
}

function getJobDuration(row: any): string {
  try {
    const startTime = row.started_at ? new Date(row.started_at) : null
    const endTime = row.finished_at ? new Date(row.finished_at) : null
    const currentTime = new Date()

    if (!startTime) return '-'

    const endTimeToUse = endTime || (row.status === 'running' ? currentTime : null)
    if (!endTimeToUse) return '-'

    const durationMs = endTimeToUse.getTime() - startTime.getTime()
    const durationSecs = Math.floor(durationMs / 1000)
    const durationMins = Math.floor(durationSecs / 60)
    const durationHours = Math.floor(durationMins / 60)

    if (durationHours > 0) return `${durationHours}h${durationMins % 60}m`
    if (durationMins > 0) return `${durationMins}m${durationSecs % 60}s`
    return `${durationSecs}s`
  } catch (e) {
    console.warn('计算任务耗时失败:', e)
    return '-'
  }
}

// 格式化完整时间（用于详情对话框）
function formatFullTime(timeStr: string): string {
  if (!timeStr) return '-'
  try {
    // 修复时区问题：确保正确解析数据库时间
    let date: Date
    if (timeStr.includes('T') || timeStr.includes('Z')) {
      // ISO格式时间，直接解析
      date = new Date(timeStr)
    } else {
      // SQLite格式时间，需要添加时区信息
      date = new Date(timeStr + 'Z') // 假设数据库存储的是UTC时间
    }

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    console.warn('格式化完整时间失败:', e, 'timeStr:', timeStr)
    return timeStr
  }
}

// 格式化筛选条件JSON
function formatFilterJson(filterJson: string): string {
  try {
    const obj = JSON.parse(filterJson)
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    console.warn('解析筛选条件JSON失败:', e)
    return filterJson
  }
}
</script>

<style scoped>
/* ✅ 页面容器和头部样式已移至公共样式 common.css */

.excel-section {
  margin-bottom: 20px;
}

.setting-description {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.import-card {
  height: 100%;
}

.import-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.import-info {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.import-info h4 {
  margin: 0 0 12px 0;
  color: #409eff;
}

.import-info ul {
  margin: 0;
  padding-left: 20px;
}

.import-info li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.required {
  color: #f56c6c;
  font-weight: 600;
}

.import-result {
  margin-bottom: 20px;
}

.result-details {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;
}

.error-list {
  margin-top: 16px;
}

.error-item {
  color: #f56c6c;
  margin-bottom: 4px;
}

.system-info {
  margin-bottom: 20px;
}

/* 任务队列优化样式 */
.job-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.job-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.job-desc {
  font-weight: 500;
  color: #303133;
  font-size: 13px;
}

.job-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.job-time {
  color: #67c23a;
  font-weight: 500;
}

.job-id {
  color: #909399;
  font-family: 'Courier New', monospace;
}

/* 原有的进度信息样式已移动到下方 */

.duration-text {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
  cursor: pointer;
}

/* 状态标签样式调整 */
:deep(.el-tag--small) {
  font-size: 11px;
  padding: 2px 6px;
}

/* 重算任务相关样式 */
.recompute-form {
  padding: 20px 0;
}

.tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

.job-progress {
  margin-top: 20px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.job-progress .el-progress {
  margin: 15px 0;
}

.progress-text {
  font-weight: 600;
  color: #409eff;
}

.job-details {
  margin-top: 15px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.time-remaining {
  color: #67c23a;
  font-weight: 500;
}

.current-record {
  margin-top: 10px;
}

.job-actions {
  margin-top: 15px;
  font-size: 14px;
  color: #67c23a;
  font-weight: 500;
}

.job-error {
  margin-top: 15px;
  font-size: 14px;
  color: #f56c6c;
  font-weight: 500;
}

/* 任务详情对话框样式 */
.job-detail {
  max-height: 500px;
  overflow-y: auto;
}

.progress-section {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;
}

.progress-section h4 {
  margin: 0 0 12px 0;
  color: #409eff;
}

.filter-section {
  margin-top: 20px;
}

.filter-section h4 {
  margin: 0 0 12px 0;
  color: #409eff;
}

.filter-json {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
  max-height: 200px;
  overflow-y: auto;
}

.error-section {
  margin-top: 20px;
}

.error-section h4 {
  margin: 0 0 12px 0;
  color: #f56c6c;
}

/* 清除记录对话框样式 */
.clear-jobs-content {
  padding: 0;
}

.clear-warning {
  margin-top: 16px;
  padding: 12px;
  background: #fff6f6;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
  color: #f56c6c;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
